import React, {
  forwardRef,
  useEffect,
  useCallback,
  useState,
  useRef,
} from "react";
import cx from "classnames";
import useGesture from "@/utils/useGesture";
import { traverseReactNode } from "@/utils/index";
import "./index.scss";

const preCls = "qh-base-swiper";

interface SwiperProps {
  /* 循环属性*/
  loop?: boolean;
  /* 默认开始位置*/
  defaultIndex?: number;
  /*自定义chilren节点*/
  children: React.ReactNode;
  /*自定义类名 */
  classNames?: string;
  /*行内样式*/
  style?: React.CSSProperties;
  /*自动播放间隙*/
  autoplayInterval?: number;
}

const MySwiper = forwardRef(
  (
    {
      loop: propsLoop = true,
      defaultIndex = 0,
      children,
      classNames,
      style,
      autoplayInterval = 3000,
    }: SwiperProps,
    ref
  ): JSX.Element => {
    const [pos, setPos] = useState(defaultIndex); // 当前图片所处的位置
    const [touch, setTouch] = useState(false);
    const idxRef = useRef(defaultIndex); // 轮播下标
    const autoPlayTimer = useRef(0);
    const trackRef = useRef<HTMLDivElement | null>(null);
    const FIXCOUNT = 2;
    const items = [] as React.ReactElement[];
    const dragRef = useRef(false);
    traverseReactNode(children, (child) => {
      if (React.isValidElement(child)) {
        items.push(child);
      }
    });

    const bind = useGesture(({ move, moving, dir }) => {
      // console.log("moving", moving);
  
      // 首先判断下 是处于触摸中还是触摸结束
      if (moving) {
        setTouch(true);
        // 跟随目标
       dragRef.current = false;
        const precent = move[0] / trackRef?.current?.offsetWidth;

        // console.log('move[0],trackRef.current.offsetWidth',move[0],trackRef.current.offsetWidth);
        setPos(idxRef.current + precent);
      } else {

        // 手势动作结束后  再将touch变为false
        window.setTimeout(() => {
          setTouch(false);
          dragRef.current = false;
        },380);
       
        if (Math.abs(move[0]) > 200) {
          // 这里有疑问 为什么x坐标＞2就算是进行了拖拽(这里我定了200)
          // console.log(move[0], "move[0]");
          dir[0] > 0 ? next() : pre();
          return;
        }else{
          dragRef.current = true;
        }
        setPos(idxRef.current);
      }
    });

    const next = useCallback(() => {
      // console.log("111");
      if (idxRef.current < items.length - 1) {
        idxRef.current = idxRef.current + 1;
      } else {
        idxRef.current = 0;
      }
      setPos(idxRef.current);
    }, [propsLoop, items.length]);

    const pre = useCallback(() => {
      if (idxRef.current > 0) {
        idxRef.current = idxRef.current - 1;
      } else {
        idxRef.current = items.length - 1;
      }
      setPos(idxRef.current);
    }, []);

    const getLoopStyle = (i: number): React.CSSProperties => {
      if (!propsLoop) {
        return;
      }
      let j = i - pos;
      if (j <= -FIXCOUNT) {
        j += items.length;
      } else if (j > items.length - FIXCOUNT) {
        // console.log(i,pos);
        j -= items.length;
        // console.log('j',j);
      }
      let noAnimate = null
    //  if(!dragRef.current){

    //   noAnimate = true;
    //  }else{
    //     noAnimate = pos !== idxRef.current || j === items.length - FIXCOUNT;
    //  }
      if(dragRef.current){
        noAnimate = false;
      }else{
        noAnimate = pos !== idxRef.current || j === items.length - FIXCOUNT;
      }


      if(i===0){
      
        console.log('不需要动画',noAnimate,touch);
        
      }
      return {
        transform: `translate3d(${j * 100}%,0,0)`,
        transition: noAnimate
          ? "none"
          : "transform 380ms cubic-bezier(0, 0, 0.5, 1)",
        left: `${-i * 100}%`,
      };
    };
    useEffect(() => {
      if (!touch) {
        autoPlayTimer.current = window.setInterval(() => {
          next();
        }, autoplayInterval);
      }
      return () => window.clearInterval(autoPlayTimer.current);
    }, [touch]);

    return (
      <div className={cx(`${preCls}`, classNames)} style={style}>
        <div className={cx(`${preCls}-items`)} ref={trackRef}>
          {items.map((item, i) => (
            <div
              className={cx(`${preCls}-item`)}
              style={getLoopStyle(i)}
              key={i}
              {...bind}
            >
              {item}
            </div>
          ))}
        </div>
      </div>
    );
  }
);

export default MySwiper;
